package server;

import static debug.Debug.DBUG;

import java.awt.Container;
import java.io.BufferedReader;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

import unit.Npc;
import unit.Player;
import unit.Unit;
import util.IntPoint;

import client.Changeable;
import client.Client;
import client.ClientControl;
import client.ClientListener;
import client.ClientPlayer;
import input.*;
import model.Map;
import model.World;
import gameloop.*;
import static debug.Debug.DBUG;

public class Server implements IntReciever {
	private World world;
	private long delay;
	private List<Client> clients;
	private java.util.Map<Integer,Changeable> changeList;
	private int idcount;
	
	public int getID() {
		return idcount++;
	}
	
	public Server(){
		clients = new CopyOnWriteArrayList<Client>();
		changeList = new HashMap<Integer,Changeable>();
		world = new World();
		delay = 1000/5;
		
		new ClientListener(this);
		
		addUnit(new Npc(getID(), new IntPoint(50,100), getMap(0)));
	}
	
	public void mainLoop() {
		long time;
		long nextTime;
		InputWindow rate = new InputWindow(this);
		
		DBUG("HELLO THERE!");
		while (true) {
			time=System.currentTimeMillis();
			nextTime=time+delay;
			// mainloop
			world.tick();
			informClients();
			
			//mainloop end
			DBUG(51, "servertick");
			if (System.currentTimeMillis() < nextTime) {
				try {
					Thread.sleep(nextTime-System.currentTimeMillis());
				} catch (Exception e) {}
			} else {
				DBUG("WARNING: LAGG");
			}
		}
	}
	
	public void recieveInt(int fps) {
		delay = 1000/fps;
	}
	public Map getMap(int id) {
		return world.getMap();
	}
	
	public void addUnit(Unit player) {
		world.addUnit(player);
		changeList.put(player.id(),player);
	}
	
	public void removeUnit(Unit u) {
		changeList.remove(u);
	}
	
	public void addClient(Client client){
		clients.add(client);
	}
	public void removeClient(Client client) {
		clients.remove(client);
	}
	public Unit getUnitByID(int id){
		return (Unit) changeList.get(id);
	}
	
	private void informClients(){
		for (Client client: clients){
			client.addChangeable(changeList);
			client.sendUpdate();
		}
	}


}
